<template>
  <div class="tool-container pt-7 pb-16">
    <div class="max-w-8xl mx-auto px-4 sm:px-6 lg:px-4">
      <div class="breadcrumbs space-x-2 text-base max-w-7xl mx-auto flex flex-wrap items-center tool-dom"
        :data-handle="tool.handle"
        :data-advertisement_id="tool.advertisement_id ? tool.advertisement_id : ''"
        data-page_position="工具详情页">
        <common-link path="/"
          class="text-gray-1000 hover:text-purple-1200 go-home">
          {{$t('home')}}
        </common-link>
        <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
          iconName='right_outlined'
          v-if="tool && tool.categories && tool.categories.length>0"></svg-icon>
        <common-link path="/category/:handle"
          :params="{ handle:tool.categories[0].handle }"
          class="text-gray-1000 hover:text-purple-1200 go-prev"
          v-if="tool && tool.categories && tool.categories.length>0">
          {{tool.categories[0].name}}
        </common-link>
        <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
          iconName='right_outlined'></svg-icon>
        <span class="text-gray-1400 text-base">
          {{toolName}}
        </span>
      </div>
      <div class="md:flex md:items-center md:justify-between mt-5">
        <div class="sm:flex sm:items-center sm:gap-10">
          <h1 class="tool-name text-gray-1000 break-words font-semibold">{{toolName}}</h1>
          <div class="flex mt-4 md:mt-0 flex-wrap gap-6">
            <a class="flex-1 flex w-full sm:w-36 sm:inline-flex mx-auto bg-blue-1400 justify-center radius-22 py-2 px-4 sm:px-6 hover:bg-blue-1500 focus:bg-blue-1600 to-view-btn"
              :href="tool.website"
              rel="dofollow"
              target="_blank"
              @click="handleExp">
              <span class="text-lg text-white whitespace-nowrap">{{$t('visit')}}</span>
            </a>

            <div class="flex items-center flex-shrink-0 text-gray-1300 cursor-pointer  hover:text-gray-2300 group to-add-or-cancle-favorites"
              :class="{'text-purple-1300': tool.user_collected, 'hover:text-purple-1400': tool.user_collected}"
              @click="addOrCancleFavorites()">
              <svg-icon className="text-xl -mt-1"
                iconName='star_filled'
                v-if="!cLoading"></svg-icon>
              <img src="@/static/images/loading.png"
                class="loading h-5 w-5"
                alt=""
                srcset=""
                v-if="cLoading">
              <span class="ml-2 text-gray-1000 text-base"
                :class="{'text-purple-1300': tool.user_collected, 'hover:text-purple-1400': tool.user_collected}">{{tool.collected_count | vReset}}</span>
            </div>
          </div>
        </div>
        <div class="mt-4 md:mt-0 md:ml-4">
          <!-- <p class="text-base text-gray-1400 mb-2 md:text-right break-words">{{$t('shareToolTo').replace('[./.]', toolName)}}</p> -->
          <min-share></min-share>
        </div>
      </div>

    </div>
    <tool-detail-first :tool="tool"
      :traffic="traffic"
      :comparisons="comparisons"
      :toolsList="toolsList"
      :recommendList="recommendList"
      :toolName="toolName"
      v-if="!tool_website || tool_website === null || JSON.stringify(tool_website) === '{}'"></tool-detail-first>

    <tool-detail-second :title="title"
      :tool="tool"
      :traffic="traffic"
      :comparisons="comparisons"
      :toolsList="toolsList"
      :tool_website="tool_website"
      :recommendList="recommendList"
      :toolName="toolName"
      v-if="tool_website && Object.prototype.toString.call(tool_website) === '[object Object]' && JSON.stringify(tool_website) !== '{}'"></tool-detail-second>

  </div>
</template>

<script>
import moment from 'moment'
import { mapActions, mapState } from 'vuex'
import mixinsExposure from '~/mixins/mixins-exposure'
import _ from 'lodash'
export default {
  name: 'ToolPage',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
        {
          hid: 'og:image',
          name: 'og:image',
          content: this.tool.image
            ? this.tool.image
            : 'https://cdn.toolify.ai/default.webp',
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
      script: [
        {
          json: {
            '@context': 'https://schema.org',
            '@type': 'SoftwareApplication',
            name: this.toolName,
            applicationCategory: 'UtilitiesApplication',
            operatingSystem: 'All',
            aggregateRating: {
              '@type': 'AggregateRating',
              ratingValue: '5',
              ratingCount: '8864',
            },
            offers: {
              '@type': 'Offer',
              price: '0',
              priceCurrency: 'USD',
            },
            headline: this.$t('detail_whatIs', { toolName: this.toolName }),
            image: [
              this.tool.image
                ? this.tool.image
                : 'https://cdn.toolify.ai/default.webp',
            ],
            dateModified: this.tool.updated_at
              ? moment(this.tool.updated_at * 1000).format(
                  'YYYY-MM-DDTHH:mm:ssZ'
                )
              : null,
            datePublished: this.tool.created_at
              ? moment(this.tool.created_at * 1000).format(
                  'YYYY-MM-DDTHH:mm:ssZ'
                )
              : null,
            author: {
              '@type': 'Organization',
              name: 'toolify',
              url: 'https://www.toolify.ai',
            },
            description: this.description,
            articleSection: 'Technology',
            mainEntityOfPage: `https://www.toolify.ai${this.$route.fullPath}`,
            publisher: {
              '@context': 'https://www.toolify.ai',
              '@type': 'Organization',
              name: 'Toolify',
              legalName: 'Toolify Inc',
              url: 'https://www.toolify.ai',
              logo: 'https://www.toolify.ai/favicon.ico',
              foundingDate: '2023',
              founders: [
                {
                  '@type': 'Organization',
                  name: 'toolify',
                },
              ],
              address: {
                '@type': 'PostalAddress',
                streetAddress: '1942 Broadway St STE 314C Boulder',
                addressLocality: 'Colorado',
                addressRegion: 'CO',
                postalCode: '80302',
                addressCountry: 'US',
              },
              contactPoint: {
                '@type': 'ContactPoint',
                contactType: 'customer support',
                email: 'business@toolify.ai',
              },
              sameAs: ['https://twitter.com/samChan3890089'],
            },
            name: this.title,
            breadcrumb: {
              '@type': 'BreadCrumbList',
              itemListElement:
                this.tool &&
                this.tool.categories &&
                this.tool.categories.length > 0
                  ? [
                      {
                        '@type': 'ListItem',
                        position: 1,
                        name: this.$t('home'),
                        item: `https://www.toolify.ai${
                          this.locale === 'en' ? '' : `/${this.locale}`
                        }`,
                      },
                      {
                        '@type': 'ListItem',
                        position: 2,
                        name: this.tool.categories[0].name,
                        item: `https://www.toolify.ai${
                          this.locale === 'en' ? '' : `/${this.locale}`
                        }/category/${this.tool.categories[0].handle}`,
                      },
                      {
                        '@type': 'ListItem',
                        position: 3,
                        name: this.toolName
                          ? this.toolName
                          : this.$route.params.handle,
                      },
                    ]
                  : [
                      {
                        '@type': 'ListItem',
                        position: 1,
                        name: this.$t('home'),
                        item: `https://www.toolify.ai${
                          this.locale === 'en' ? '' : `/${this.locale}`
                        }`,
                      },
                      {
                        '@type': 'ListItem',
                        position: 2,
                        name: this.toolName
                          ? this.toolName
                          : this.$route.params.handle,
                      },
                    ],
            },
            mainEntity: this.faqArr,
          },
          type: 'application/ld+json',
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    if (process.server) {
    }
    try {
      let [toolsRes, recommendRes] = await Promise.all([
        $axiosApi.getToolDetail(encodeURIComponent(params.handle), {
          modules: 'related_tools',
        }),
        /* $axiosApi.searchGetAd({
          limit: 4,
        }), */
        /* await $axiosApi.getTools({
          order_by: 'recommended_at',
          page: 1,
          per_page: 100,
          only_recommend: 1,
        }), */
      ])

      let toolsList,
        tool,
        traffic,
        tool_website = null,
        comparisons = null,
        faqArr = []
      let description, title
      let toolName
      let recommendList = []
      if (toolsRes.code === 200) {
        tool = toolsRes.data.tool
        traffic = toolsRes.data.traffic
        tool_website = toolsRes.data.tool_website
        comparisons = toolsRes.data.comparisons
        toolsList =
          toolsRes.data.related_tools && toolsRes.data.related_tools.length > 0
            ? toolsRes.data.related_tools
            : []

        recommendList =
          toolsRes.data.tool_ad && toolsRes.data.tool_ad.length > 0
            ? toolsRes.data.tool_ad.slice(0, 4)
            : []

        toolName = tool.name
        if (tool.website_name) {
          toolName = tool.website_name
        }

        if (tool_website) {
          faqArr.push({
            '@type': 'Question',
            name: app.i18n.t('detail_whatIs', { toolName: toolName }),
            acceptedAnswer: {
              '@type': 'Answer',
              text: tool_website.what_is
                ? tool_website.what_is
                : tool.description,
            },
          })
          if (tool_website.how_to_use) {
            faqArr.push({
              '@type': 'Question',
              name: app.i18n.t('detail_how_to_use', { toolName: toolName }),
              acceptedAnswer: {
                '@type': 'Answer',
                text: tool_website.how_to_use,
              },
            })
          }
          if (Array.isArray(tool_website.faq) && tool_website.faq.length > 0) {
            tool_website.faq.forEach((item) => {
              faqArr.push({
                '@type': 'Question',
                name: item.q,
                acceptedAnswer: {
                  '@type': 'Answer',
                  text: item.a,
                },
              })
            })
          }
        } else if (tool.description) {
          faqArr.push({
            '@type': 'Question',
            name: app.i18n.t('detail_whatIs', { toolName: toolName }),
            acceptedAnswer: {
              '@type': 'Answer',
              text: tool.description,
            },
          })
        }
        if (tool.description && typeof tool.description === 'string') {
          description = `${toolName}: ${tool.description} - Toolify`
          /* let descArr = tool.description.split('.')
          if (descArr && descArr.length >= 1) {
            description = `${descArr[0]}. ${app.i18n.t('common_title', {
              toolName: toolName ? toolName : app.i18n.t('detail_aITool'),
            })}`
          } */
        }
      } else {
        if (toolsRes && toolsRes.code && toolsRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(toolsRes && toolsRes.code && toolsRes.code === 401)) {
          error({
            message: app.i18n.t('error_401'),
            statusCode: toolsRes.code,
          })
        }
      }

      /* let oldRecommendList = []
      if (oldRecommendRes.code === 200) {
        oldRecommendList =
          oldRecommendRes.data.data && oldRecommendRes.data.data.length > 0
            ? oldRecommendRes.data.data
            : []
      } */

      let date = new Date()
      let fullYear = date.getFullYear()

      if (toolName) {
        title = app.i18n.t('detail_tab_title', {
          toolName: toolName,
          fullYear: fullYear,
        })

        if (!description) {
          description = app.i18n.t('common_desc', { toolName: toolName })
        }
      } else {
        title = app.i18n.t('common_title')
      }

      if (!description) {
        description = app.i18n.t('common_desc')
      }

      return {
        toolsList,
        tool,
        title,
        description,
        traffic,
        comparisons,
        tool_website,
        recommendList,
        faqArr,
        toolName,
      }
    } catch (err) {
      console.log(err)
    }
  },
  filters: {
    vReset: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val <= 1000) {
          return val
        } else if (val > 1000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return val
      }
    },
  },
  watch: {
    tool: {
      handler() {
        if (this.tool && this.tool.image) {
          let iSrc = this.tool.image
          if (iSrc.indexOf('x-oss-process') === -1) {
            iSrc = `${iSrc}${
              iSrc.indexOf('?') === -1 ? '?' : '&'
            }x-oss-process=image/resize,l_1000,m_lfit`
          }
          if (
            iSrc.indexOf('https://nav-station.oss-accelerate.aliyuncs.com') >= 0
          ) {
            iSrc = iSrc.replace(
              'https://nav-station.oss-accelerate.aliyuncs.com',
              'https://cdn-images.toolify.ai'
            )
          }
          this.tool.image = iSrc
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  mixins: [mixinsExposure],
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      tool: {},
      traffic: {},
      comparisons: null,
      toolsList: [],
      tool_website: null,
      title: null,
      description: null,
      cLoading: false,

      faqArr: [],

      //推荐的工具
      recommendList: [],

      toolName: null,
    }
  },
  methods: {
    ...mapActions(['exposure']),
    getLocaleText(val, val_locales) {
      if (
        Object.prototype.toString.call(val_locales) === '[object Object]' &&
        typeof val_locales[this.locale] != 'undefined' &&
        val_locales[this.locale] !== null &&
        val_locales[this.locale] !== ''
      ) {
        return val_locales[this.locale]
      } else {
        return val
      }
    },
    async addOrCancleFavorites() {
      this.cLoading = true
      try {
        try {
          let res

          switch (this.tool.user_collected) {
            case 0:
              res = await this.$axiosApi.postFavorites({
                handle: encodeURIComponent(this.$route.params.handle),
              })
              break
            case 1:
              res = await this.$axiosApi.deleteFavorites({
                handle: encodeURIComponent(this.$route.params.handle),
              })
              break
            default:
              console.log('error')
          }

          this.cLoading = false
          if (res && res.code === 200) {
            this.$message.success(
              this.tool.user_collected
                ? this.$i18n.t('cancelFavoritesSuccess')
                : this.$i18n.t('addFavoritesSuccess')
            )
            this.tool.user_collected = this.tool.user_collected ? 0 : 1

            this.tool.collected_count = this.tool.user_collected
              ? parseInt(this.tool.collected_count) + 1
              : parseInt(this.tool.collected_count) - 1
          }
        } catch (error) {
          this.cLoading = false
          console.log(error)
        }
      } catch (error) {}
    },

    handleExp: _.throttle(function () {
      let exporeData = this.getExporeData(this.tool, null, null, false, {
        target_url: this.tool.website,
        page_position: 'Open Site',
      })
      this.exposure({
        ...exporeData,
      })
    }, 2000),
  },
}
</script>
<style lang='scss' scoped>
.tool-container {
  .tool-name {
    font-size: 34px;
    line-height: 40px;
  }
  .text-26,
  ::v-deep .text-26 {
    line-height: 32px;
  }
}
</style>
